<template>
  <div>
    <el-dialog
      title="新增安装点"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="closeEditDialog"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form
        :model="addInfo"
        :rules="rules"
        ref="refAddInfo"
        label-width="100px"
      >
        <!-- <el-form-item size="small" label="布防状态" prop="isDefence">
          <el-select v-model="addInfo.isDefence" placeholder="请选择布防状态" style="width: 360px">
            <el-option v-for="item in isDefenceArr" :key="item.id" :label="item.label" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item size="small">
          <el-radio v-model="radio" label="1">单个添加安装点</el-radio>
          <el-radio v-model="radio" label="2" style="margin-left: 20px"
            >批量添加安装点</el-radio
          >
        </el-form-item>

        <el-form-item size="small" label="组织机构" prop="orgId">
          <el-select
            v-model="addInfo.orgId"
            filterable
            placeholder="请选择单位"
            style="width: 360px"
            class="elSelect"
            @change="projectchange"
            v-loadMore="loadMore"
          >
            <el-option
              v-for="(item, i) in projectList"
              :key="i"
              :label="item.orgName"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading"
              :style="loading ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>

        <el-form-item size="small" label="建筑物" prop="parentId">
          <el-select
            v-model="addInfo.parentId"
            filterable
            placeholder="请选择建筑物"
            style="width: 360px"
            @change="projectchange2"
            v-loadMore="loadMore2"
          >
            <el-option
              v-for="item in buildings"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading2"
              :style="loading2 ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>

        <!-- v-if="flag" -->
        <el-form-item size="small" label="楼层" prop="pid">
          <el-select
            v-model="addInfo.pid"
            filterable
            placeholder="请选择楼层"
            style="width: 360px"
            v-loadMore="loadMore3"
          >
            <el-option
              v-for="item in floor"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading3"
              :style="loading3 ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>

        <el-form-item
          size="small"
          label="安装点名称"
          prop="name"
          v-if="radio == '1'"
        >
          <el-input
            clearable
            v-model.trim="addInfo.name"
            placeholder="请输入安装点名称"
            maxlength="30"
          ></el-input>
        </el-form-item>

        <el-form-item
          size="small"
          :label="index == 0 ? '安装点' : ''"
          v-for="(domain, index) in addInfo.floorsId"
          :key="domain.key"
          :prop="'floorsId.' + index + '.id2'"
          :rules="{
            required: true,
            message: '安装点数不能为空',
            trigger: 'blur',
          }"
          v-show="radio == '2'"
        >
          <div style="display: flex; justify-content: space-between">
            <!-- oninput="if(isNaN(value)) { value = null } {if(value>49)value=49}" -->
            <el-input
              type="input"
              maxlength="2"
              v-model.trim="domain.id1"
              style="width: 30%"
              :placeholder="index == 0 ? '1' : ''"
              oninput=" { value=value.replace(/[^\-\d]/g, '') } { value=value.replace(/\-{2,}/g, '-') } { value=value.replace(/(\d)\-/g, '$1') }
            { value=value.replace(/-(0+)/g, '0') } { value=value.replace(/^0+(\d)/, '$1') }
            {if(value<-3)value=-3} {if(value=='0')value=1} {if(value=='-0')value=-1} {if(value>49)value=49}"
            >
            </el-input>
            至
            <el-input
              type="input"
              style="width: 30%"
              maxlength="2"
              v-model.trim="domain.id2"
              :placeholder="index == 0 ? '5' : ''"
              oninput="{ value=value.replace(/[^\-\d]/g, '') } { value=value.replace(/\-{2,}/g, '-') } { value=value.replace(/(\d)\-/g, '$1') }
            { value=value.replace(/-(0+)/g, '0') } { value=value.replace(/^0+(\d)/, '$1') }
             {if(value<-3)value=-3} {if(value=='0')value=1} {if(value=='-0')value=-1} {if(value>50)value=50}"
            ></el-input>
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="bottom"
              >
                <i
                  class="el-icon-remove-outline zuobiao2"
                  style="font-size: 20px; cursor: pointer"
                  @click.prevent="removeFloor(domain)"
                ></i>
              </el-tooltip>
            </div>
          </div>
        </el-form-item>

        <el-form-item
          size="small"
          v-show="this.addInfo.floorsId.length < 2 && radio == '2'"
        >
          <el-tooltip
            class="item"
            effect="dark"
            content="新增楼层"
            placement="bottom"
          >
            <i
              class="el-icon-circle-plus-outline zuobiao2"
              style="font-size: 20px; cursor: pointer"
              @click="addFloor"
            ></i>
          </el-tooltip>
        </el-form-item>

        <!-- 
        <el-form-item size="small" label="">
          <el-button icon="el-icon-map-location" @click="openMap">地图选点</el-button>
        </el-form-item>
-->
        <!-- <el-form-item size="small" label="地区" prop="provinceCityAreaValue">
          <el-cascader v-model.trim="addInfo.provinceCityAreaValue" placeholder="请选择省市区" :options="provinceCityAreaData"
            :props="{ expandTrigger: 'hover' }" filterable @change="changeProvinceCityArea" style="width: 330px">
          </el-cascader>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog" class="cancel-button">取 消</el-button>
        <el-button
          size="small"
          @click="editSubmit"
          v-preventReClick="1000" class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- <div class="mapLoc" v-if="isShowMap">
      <iframe :src="reqUrl" v-if="isShowMap" frameborder="0" class="iframe" seamless scrolling="no"></iframe>
    </div> -->
  </div>
</template>

<script>
import { handleTree } from "@utils/trans-tree";
import { provinceCityAreaArray } from "@/utils/province-city-area";
import {
  reqSpaceManager,
  reqOrgList,
  reqParkList,
  reqBatchAdd,
} from "@/api/api";
import { mapState } from "vuex";
import treeselect from "@riophae/vue-treeselect"; //树形选择器
import "@components/vue-treeselect.less"; //树形选择器
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect"; //Vue-Treeselect三级动态加载
import loadMore from "@mixin/loadMore";

export default {
  name: "add",
  // props: ["floor"],
  components: { treeselect },
  mixins: [loadMore],
  data() {
    const validatorLocation = (rule, value, callback) => {
      if (
        !this.addInfo.province ||
        this.addInfo.province == "省" ||
        !this.addInfo.city ||
        this.addInfo.city == "市" ||
        !this.addInfo.area ||
        this.addInfo.area == "区"
      ) {
        callback(new Error("请选择省市区"));
      }
    };
    return {
      normalizer(node) {
        return {
          id: node.id,
          label: node.orgName,
          children: node.children,
        };
      },
      flag: false,
      floor: [],
      radio: "1",
      buildings: [],
      projectList: [], //单位数据
      provinceCityAreaData: provinceCityAreaArray,
      dialogVisible: false,
      addInfo: {
        isDefenceArr: "0",
        name: "",
        address: "",
        lng: "",
        lat: "",
        orgId: null,
        isDefence: "",
        buildingType: "3",
        childrenName: [],
        floorsId: [
          {
            id1: "1",
            id2: "5",
          },
        ],
        pid: "",
        parentId: "",
      },
      isDefenceArr: [
        {
          id: "0",
          label: "撤防",
        },
        {
          id: "1",
          label: "布防",
        },
      ],
      // 表单验证规则
      rules: {
        name: [
          {
            required: true,
            message: "请输入安装点名称",
            trigger: "blur",
          },
        ],
        // provinceCityAreaValue: [
        //   {
        //     type: "array",
        //     required: true,
        //     message: "请选择省市区",
        //     trigger: "change",
        //   },
        // ],
        orgId: [
          {
            required: true,
            message: "请选择单位",
            trigger: ["blur", "change"],
          },
        ],
        pid: [
          {
            required: true,
            message: "请选择楼层",
            trigger: "change",
          },
        ],
        parentId: [
          {
            required: true,
            message: "请选择建筑物",
            trigger: ["blur", "change"],
          },
        ],
        isDefence: [
          {
            required: true,
            message: "请选择布防状态",
            trigger: "change",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入详细地址",
            trigger: "blur",
          },
        ],
      },
      reqUrl:
        "https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1",
      // isShowMap: false,
      loading: false,
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      sysInstanceIndex2: 1,
      sysInstanceTotalPages2: 10,
      loading2: false,
      sysInstanceIndex3: 1,
      sysInstanceTotalPages3: 10,
      loading3: false,
    };
  },
  watch: {},
  computed: {
    ...mapState(["user"]),
  },
  methods: {
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
        return;
      this.sysInstanceIndex++;
      this.loading = true;
      // 获取列表数据的方法
      await this.OrgList();
      this.loading = false;
    },
    // 获取单位列表
    async OrgList() {
      var res = await reqOrgList( {
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.projectList =res.data.rows
    },
    // 根据单位查询建筑物
    async projectchange(e) {
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.addInfo.parentId = "";
      this.buildings = [];
      this.floor = [];
      this.addInfo.pid = "";
      await this.SpaceManager2();
    },
    // 根据建筑物查询楼层
    projectchange2() {
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.flag = true;
      this.addInfo.pid = "";
      this.floor = [];
      this.SpaceManager();
    },
    async loadMore3() {
      if (this.sysInstanceIndex3 >= Math.ceil(this.sysInstanceTotalPages3 / 10))
        return;
      this.sysInstanceIndex3++;
      this.loading3 = true;
      // 获取列表数据的方法
      await this.SpaceManager();
      this.loading3 = false;
    },
    // 楼层列表
    async SpaceManager() {
      let res = await reqSpaceManager(this.sysInstanceIndex3, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        metaCode: 2,
        orgId: this.addInfo.orgId,
        parentId: this.addInfo.parentId,
        isStatistics: 0,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages3 = res.data.total;
      this.floor = [...this.floor, ...res.data.rows];
    },

    async loadMore2() {
      if (this.sysInstanceIndex2 >= Math.ceil(this.sysInstanceTotalPages2 / 10))
        return;
      this.sysInstanceIndex2++;
      this.loading2 = true;
      // 获取列表数据的方法
      await this.SpaceManager2();
      this.loading2 = false;
    },
    // 建筑物列表
    async SpaceManager2() {
      let res = await reqSpaceManager(this.sysInstanceIndex2, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        metaCode: 1,
        orgId: this.addInfo.orgId,
        isStatistics: 0,
        // parentId: this.addInfo.parentId,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages2 = res.data.total;
      this.buildings = [...this.buildings, ...res.data.rows];
    },
    addFloor() {
      this.$notify.closeAll();
      // if (this.addInfo.floorsId.length > 1) return this.$modal.notifyWarning('最多只允许添加两个楼层信息');
      this.addInfo.floorsId.push({
        id1: "",
        id2: "",
        key: Date.now(),
      });
    },
    removeFloor(item) {
      // console.log(item);
      // console.log(this.addInfo.floorsId.length);
      if (this.addInfo.floorsId.length == 1) return;
      var index = this.addInfo.floorsId.indexOf(item);
      if (index !== -1) {
        this.addInfo.floorsId.splice(index, 1);
      }
    },

    // 新版省市区获取
    // changeProvinceCityArea(val) {
    //   this.addInfo.province = val[0];
    //   this.addInfo.city = val[1];
    //   this.addInfo.area = val[2];
    //   this.addInfo.provinceCityAreaValue = [val[0], val[1], val[2]];
    // },

    openMap() {
      this.$store.commit("saveIsShowMap", true);
      // this.isShowMap = true
    },
    // 点击
    async editSubmit() {
      this.$refs.refAddInfo.validate(async (valid) => {
        if (valid) {
          if (this.radio == "1") {
            let nameList = [this.addInfo.name];
            const res2 = await reqBatchAdd({
              pid: this.addInfo.pid,
              nameList: nameList,
            });
            if (res2.code !== 20000)
              return this.$modal.notifyWarning(res2.message);
          } else {
            let arr = [];
            let flag = false;
            let index = 0;
            let flag2 = false;
            this.addInfo.floorsId.forEach((item, i) => {
              // console.log(item);
              if (item.id1 == "" || item.id2 == "") {
                flag2 = true;
                return;
              }
              if (item.id1 > item.id2) {
                index = i + 1;
                flag = true;
                return;
              }
              for (let i = item.id1; i <= item.id2; i++) {
                // console.log(i);
                if (i != "") {
                  arr.push(`${i}`);
                }
              }
            });
            if (flag2) return this.$modal.notifyWarning("楼层数不能为空");
            //  if (flag) return this.$modal.notifyWarning(`第${index}项结束楼层小于开始楼层，请检查！`)
            let nameList = Array.from(new Set(arr));
            // console.log(nameList);
            if (nameList.length == 0)
              return this.$modal.notifyWarning("安装点不能为空");
            // console.log(this.addInfo.floorsId);
            const res2 = await reqBatchAdd({
              pid: this.addInfo.pid,
              nameList: nameList,
            });
            if (res2.code !== 20000)
              return this.$modal.notifyWarning(res2.message);
          }

          this.$modal.notifySuccess("添加安装点成功");
          this.$parent.getreqParkList(); //更新安装点列表
          this.closeEditDialog();
        }
      });
      // this.$refs.refAddInfo.validate(async (valid) => {
      //   if (valid) {
      //     const res = await reqAdd(this.addInfo);
      //     if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      //      this.$modal.notifySuccess("添加园区成功");
      //     this.dialogVisible = false;
      //     this.$parent.getreqParkList(); //更新安装点列表
      //   }
      // });
    },
    // 点击关闭弹框
    closeEditDialog() {
      this.flag = false;
      this.radio = "1";
      this.projectList = [];
      this.buildings = [];
      this.floor = [];
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.sysInstanceIndex3 = 1;
      this.sysInstanceTotalPages3 = 10;
      this.addInfo = {
        isDefenceArr: "0",
        name: "",
        address: "",
        lng: "",
        lat: "",
        orgId: null,
        isDefence: "",
        buildingType: "3",
        childrenName: [],
        floorsId: [
          {
            id1: "1",
            id2: "5",
          },
        ],
        pid: "",
        parentId: "",
      };
      this.$refs.refAddInfo.resetFields();
      this.dialogVisible = false;
    },
  },
  deactivated() {
    if(this.$refs.refAddInfo!=null){
      this.closeEditDialog();
    }
  },
};
</script>

<style lang="less" scoped>
@import url("../../common.less");

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 2016;
  // background: red;
  // opacity: 0.5;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束
::v-deep .el-radio {
  color: @primaryThemeTxtColor2;
}
::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #7367f0;
}
::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #7367f0;
  background: #7367f0;
}
.zuobiao2 {
  color: @primaryTxtcolor;
}
</style>